﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using KeanuMvc.Reference;
using HISModels.Entities;
using System.Net.Http;
using Newtonsoft.Json;
using System.Data.Objects;
using HISModels.ViewModel;

namespace HISRestServices.Services {

    [ServiceContract()]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class Physician : BaseServices, IDisposable {

        #region Field
        private HttpStatusCode statusCode = new HttpStatusCode();
        private string detailMessage = string.Empty;
        #endregion

        #region Doctor

        [WebGet(UriTemplate = "doctor/")]
        public HttpResponseMessage<List<Doctor>> GetListDoctor() {
            HttpResponseMessage<List<Doctor>> returnValue = null;
            List<Doctor> listdoctor = null;
            try {
                listdoctor = AppContext.Doctors.Include("Employee").Where(p => p.RecordStatus == 1).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            returnValue = new HttpResponseMessage<List<Doctor>>(statusCode);
            returnValue.Content = new ObjectContent<List<Doctor>>(listdoctor);
            if (listdoctor == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebGet(UriTemplate = "doctor/{id}")]
        public HttpResponseMessage<ViewDataDoctor> GetDoctorByID(int id) {

            HttpResponseMessage<ViewDataDoctor> returnValue = null;
            ViewDataDoctor data = null;

            try {
                data = new ViewDataDoctor();
                var a = from b in AppContext.Doctors
                        join g in AppContext.Employees on b.EmployeeId equals g.Id
                        join c in AppContext.DoctorSpecRels on b.Id equals c.DoctorId
                        join d in AppContext.RefSubSpecialists on c.SubSpecialistId equals d.Id
                        join e in AppContext.RefSpecialists on d.SpecialistId equals e.Id
                        join f in AppContext.RefSpecialistGroups on e.GroupSpecialistId equals f.Id
                        where b.Id == id && b.RecordStatus == 1
                        select new ViewDataDoctor {
                            DoctorId = b.Id,
                            EmployeeId = g.Id,
                            EmployeeNumber = g.EmployeeNumber,
                            DoctorCode = b.CodeValue,
                            DoctorSpecRelId = c.Id,
                            FirstName = g.FirstName,
                            LastName = g.LastName,
                            GroupSpecialistId = f.Id,
                            GroupSpecialist = f.NameValue,
                            SubSpecialistId = d.Id,
                            SubSpecialist = d.NameValue,
                            SpecialistId = e.Id,
                            Specialist = e.NameValue,
                            RecordStatus = b.RecordStatus
                        };
                data = (a).First();

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<ViewDataDoctor>(statusCode);
                returnValue.Content = new ObjectContent<ViewDataDoctor>(data);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebGet(UriTemplate = "doctorid/{userid}")]
        public HttpResponseMessage<AnonymousHeaderDetail> GetDoctorIDByUserID(string userid) {

            HttpResponseMessage<AnonymousHeaderDetail> returnValue = null;
            AnonymousHeaderDetail data = null;

            try {
                data = new AnonymousHeaderDetail();

                var a = from b in AppContext.Doctors
                        join f in AppContext.Employees on b.EmployeeId equals f.Id
                        join d in AppContext.MemberEmployees on f.Id equals d.EmployeeId
                        join e in AppContext.SysMemberships on d.MembershipId equals e.Id
                        select new {
                            userid = e.UserId,
                            doctorid = b.Id
                        };
                a = a.Where(p => p.userid == userid);

                data.Detail = a;

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<AnonymousHeaderDetail>(statusCode);
            returnValue.Content = new ObjectContent<AnonymousHeaderDetail>(data);
            if (data == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/paging/")]
        public HttpResponseMessage<DataTablesNet> GetDoctorAllPost(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] data = null;

            int specialistid = 0;
            string name = string.Empty;
            string code = string.Empty;
            int HuId = Hospital.Id;


            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                data = pagingSearch.sSearch.Split(';');

                if (data.Count() > 0) {

                    specialistid = data[0].Split('=')[1].NullSafeToString() != string.Empty ? Convert.ToInt32(data[0].Split('=')[1]) : 0;
                    name = data[1].Split('=')[1].NullSafeToString().Trim();
                    code = data[2].Split('=')[1].NullSafeToString().Trim();
                }

                var a = from b in AppContext.Doctors
                        join i in AppContext.Employees on b.EmployeeId equals i.Id
                        join c in AppContext.DoctorSpecRels on b.Id equals c.DoctorId
                        join d in AppContext.RefSubSpecialists on c.SubSpecialistId equals d.Id
                        join f in AppContext.RefSpecialists on d.SpecialistId equals f.Id
                        join g in AppContext.RefSpecialistGroups on f.GroupSpecialistId equals g.Id
                        join e in AppContext.DoctorHuRels on b.Id equals e.DoctorId
                        where b.RecordStatus == 1 //&& e.HospitalUnitId == HuId
                        select new {
                            b.Id,
                            DoctorCode = b.CodeValue,
                            i.FirstName,
                            i.LastName,
                            GroupSpecialist = g.NameValue,
                            SubSpecialist = d.NameValue,
                            SpecialistId = f.Id,
                            Specialist = f.NameValue,
                            spec = (g.NameValue.Trim() + " " + d.NameValue.Trim() + " " + f.NameValue.Trim()).Trim(),
                            DoctorName = (i.FirstName.Trim() + " " + i.LastName.Trim()).Trim()
                        };
                paging.iTotalRecords = a.Count();
                a = a.Where(p => (p.FirstName.Contains(name) || p.LastName.Contains(name) || p.DoctorName.Contains(name)) &&
                                  (p.DoctorCode.Contains(code)));

                if (specialistid != 0) {
                    a = a.Where(d => d.SpecialistId == specialistid);
                }


                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/external/paging/")]
        public HttpResponseMessage<DataTablesNet> GetDoctorExtPost(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] data = null;

            string specialist = string.Empty;
            string name = string.Empty;
            string code = string.Empty;
            int HuId = Hospital.Id;


            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                data = pagingSearch.sSearch.Split(';');

                if (data.Count() > 0) {
                    specialist = data[0].Split('=')[1].NullSafeToString();
                    name = data[1].Split('=')[1].NullSafeToString();
                    code = data[2].Split('=')[1].NullSafeToString();
                }

                var a = from b in AppContext.DoctorExts.Include("Addresses")
                        select b;

                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.FullName.Contains(name) && p.DoctorCode.Contains(code) && p.Specialist.Contains(specialist));


                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/external/")]
        public HttpResponseMessage<DoctorExt> InsertDoctorExt(DoctorExt paramObject) {
            HttpResponseMessage<DoctorExt> returnValue = null;
            try {
                if (AppContext.DoctorExts.Where(d => d.DoctorCode == paramObject.DoctorCode).Count() > 0) {
                    detailMessage = "Code of Doctor is already exist in Database!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;

                    foreach (var addr in paramObject.Addresses) {
                        AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    }

                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DoctorExt>(statusCode);
                returnValue.Content = new ObjectContent<DoctorExt>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/master/paging/")]
        public HttpResponseMessage<DataTablesNet> GetDoctorMasterPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] param = null;

            string subspecialist = string.Empty;
            string specialist = string.Empty;
            int huid = 0;
            int groupspecialistid = 0;
            RefHu hospital = Hospital;
            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                param = pagingSearch.sSearch.Split(';');

                if (param.Count() > 0) {
                    huid = param[0].Split('=')[1].NullSafeToString() == string.Empty ? Convert.ToInt32(param[0].Split('=')[1]) : hospital.Id;

                    groupspecialistid = Convert.ToInt32(param[1].Split('=')[1]);
                    subspecialist = param[2].Split('=')[1].NullSafeToString().Trim();
                    specialist = param[3].Split('=')[1].NullSafeToString().Trim();
                }

                var a = from b in AppContext.Doctors
                        join h in AppContext.Employees on b.EmployeeId equals h.Id
                        join c in AppContext.DoctorSpecRels on b.Id equals c.DoctorId
                        join d in AppContext.RefSubSpecialists on c.SubSpecialistId equals d.Id
                        join f in AppContext.RefSpecialists on d.SpecialistId equals f.Id
                        join g in AppContext.RefSpecialistGroups on f.GroupSpecialistId equals g.Id
                        join e in AppContext.DoctorHuRels on b.Id equals e.DoctorId
                        where b.RecordStatus == 1
                        select new {
                            b.Id,
                            DoctorCode = b.CodeValue,
                            h.FirstName,
                            h.LastName,
                            FullName = h.FirstName + " " + h.LastName,
                            GroupSpecialistId = g.Id,
                            GroupSpecialist = g.NameValue,
                            SubSpecialist = d.NameValue,
                            Specialist = d.NameValue,
                            DoctorName = h.FirstName + " " + h.LastName,
                            e.HospitalUnitId

                        };
                paging.iTotalRecords = a.Count();

                if (huid != 0) {
                    a = a.Where(d => d.HospitalUnitId == huid);
                }

                if (groupspecialistid != 0) {
                    a = a.Where(d => d.GroupSpecialistId == groupspecialistid);
                }

                a = a.Where(p => (p.SubSpecialist.Contains(subspecialist) || p.Specialist.Contains(specialist)));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/employee/paging/")]
        public HttpResponseMessage<DataTablesNet> GetEmployeesDoctorPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] param = null;

            string employeenumber = string.Empty;
            string employeename = string.Empty;
            //int huid = 0;
            //RefHu hospital = Hospital;
            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                param = pagingSearch.sSearch.Split(';');

                if (param.Count() > 0) {
                    //huid = param[0].Split('=')[1].NullSafeToString() == string.Empty ? Convert.ToInt32(param[0].Split('=')[1]) : hospital.Id;
                    employeenumber = param[0].Split('=')[1].NullSafeToString().Trim();
                    employeename = param[1].Split('=')[1].NullSafeToString().Trim();
                }

                var a = from b in AppContext.Doctors
                        join h in AppContext.Employees on b.EmployeeId equals h.Id
                        join c in AppContext.Departements on h.DepartementId equals c.Id
                        join d in AppContext.Positions on h.Position equals d.Id
                        where h.RecordStatus == 1 && b.RecordStatus == 1 && h.Position == 1
                        select new { 
                           h.Id,
                           EmployeeNo = h.EmployeeNumber,
                           EmplloyeeName = h.TitleBeforeName + " " + h.FirstName + " " + h.LastName + " " + h.TitleAfterName,
                           h.FirstName,
                           h.LastName
                        };

                paging.iTotalRecords = a.Count();

                //if (huid != 0) {
                //    a = a.Where(d => d.HospitalUnitId == huid);
                //}

                a = a.Where(p => (p.FirstName.Contains(employeename) || p.LastName.Contains(employeename)) && p.EmployeeNo.Contains(employeenumber));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/")]
        public HttpResponseMessage<Doctor> InsertDoctor(Doctor paramObject) {
            HttpResponseMessage<Doctor> returnValue = null;
            try {
                if (AppContext.Doctors.Where(d => d.CodeValue == paramObject.CodeValue).Count() > 0) {
                    detailMessage = "Code of Doctor is already exist in Database!";
                } else {
                    string rawcode = paramObject.CodeValue;
                    paramObject.CodeValue = NumberGenerator.Instance.GetDoctorCode(AppContext, rawcode);
                    paramObject.RecordStatus = 1;
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;

                    foreach (var docspecrel in paramObject.DoctorSpecRels) {
                        AppContext.Entry(docspecrel).State = System.Data.EntityState.Added;
                    }

                    foreach (var dochurel in paramObject.DoctorHuRels) {
                        AppContext.Entry(dochurel).State = System.Data.EntityState.Added;
                    }

                    AppContext.SaveChanges(UserId);
                }
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Doctor>(statusCode);
                returnValue.Content = new ObjectContent<Doctor>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "doctor/")]
        public HttpResponseMessage<Doctor> UpdateDoctor(Doctor paramObject) {
            HttpResponseMessage<Doctor> returnValue = null;
            try {
                if (AppContext.Doctors.Where(d => d.CodeValue == paramObject.CodeValue && d.Id != paramObject.Id).Count() > 0) {
                    detailMessage = "Code of Doctor is already exist in Database!";
                } else {
                    foreach (var docspecrel in paramObject.DoctorSpecRels) {
                        AppContext.Entry(docspecrel).State = System.Data.EntityState.Modified;
                    }

                    //foreach (var dochurel in paramObject.DoctorHuRels) {
                    //    AppContext.DoctorHuRels.Attach(dochurel);
                    //    AppContext.Entry(dochurel).State = System.Data.EntityState.Modified;
                    //}

                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                }
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Doctor>(statusCode);
                returnValue.Content = new ObjectContent<Doctor>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "doctor/")]
        public HttpResponseMessage<Doctor> RemoveDoctor(int id) {
            HttpResponseMessage<Doctor> returnValue = null;
            Doctor doctor = null;
            try {
                doctor = AppContext.Doctors.Where(d => d.Id == id).First();

                doctor.RecordStatus = 0;
                AppContext.Entry(doctor).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Doctor>(statusCode);
                returnValue.Content = new ObjectContent<Doctor>(doctor);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/worklist/")]
        public HttpResponseMessage<DataTablesNet> GetWorklistDoctor(PostDataTablesNet pagingSearch) {
            return GetWorklistDoctor("Default", pagingSearch);
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/worklist/istreated/")]
        public HttpResponseMessage<DataTablesNet> GetWorklistDoctorIsTreated(PostDataTablesNet pagingSearch) {

            return GetWorklistDoctor("IsTreated", pagingSearch);
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/worklist/untreated/")]
        public HttpResponseMessage<DataTablesNet> GetWorklistDoctorUnTreated(PostDataTablesNet pagingSearch) {
            return GetWorklistDoctor("UnTreated", pagingSearch);
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/worklist/last7days/")]
        public HttpResponseMessage<DataTablesNet> GetWorklistDoctorWeek(PostDataTablesNet pagingSearch) {
            return GetWorklistDoctor("last7days", pagingSearch);
        }

        /// <summary>
        /// Get worklists of doctor 
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="pagingSearch"></param>
        /// <returns></returns>
        private HttpResponseMessage<DataTablesNet> GetWorklistDoctor(string methodName, PostDataTablesNet pagingSearch) {
            DataTablesNet paging = new DataTablesNet();
            paging.sEcho = pagingSearch.sEcho;

            string[] param = pagingSearch.sSearch.Split(';');

            int doctor_id = 0;
            int lob_id = 0;
            int patient_id = 0;
            string reg_time = string.Empty;
            string keywords = string.Empty;
            string location = string.Empty;
            RefHu hospital = Hospital;
            int HuId = Hospital.Id;
            string hospitalcode = HospitalCode;


            if (!string.IsNullOrEmpty(param[0].Split('=')[1]))
                doctor_id = Convert.ToInt32(param[0].Split('=')[1]);

            if (!string.IsNullOrEmpty(param[1].Split('=')[1]))
                lob_id = Convert.ToInt32(param[1].Split('=')[1]);

            if (!string.IsNullOrEmpty(param[2].Split('=')[1]))
                patient_id = Convert.ToInt32(param[2].Split('=')[1]);

            reg_time = param[3].Split('=')[1].NullSafeToString();

            keywords = param[4].Split('=')[1].NullSafeToString();

            if (!string.IsNullOrEmpty(param[5].Split('=')[1]))
                location = param[5].Split('=')[1].NullSafeToString();


            var a = from b in AppContext.Patients
                    join c in AppContext.PatientRegs on b.Id equals c.PatientId
                    join d in AppContext.RefGenders on b.GenderId equals d.Id
                    join e in AppContext.DoctorRegRels on c.Id equals e.RegistrationId
                    join f in AppContext.HuLobRels on c.HuLobRelId equals f.Id
                    join g in AppContext.RefLobs on f.LineOffBusinessUnitID equals g.Id
                    where e.DoctorId == doctor_id  //&& DateTime.Compare(c.RegistrationTime, DateTime.Now) >= 0
                    select new {
                        patientid = b.Id,
                        lob = g.CodeValue,
                        mrno = b.MedicalRecordNumber,
                        b.FirstName,
                        b.MiddleName,
                        b.LastName,
                        name = b.FirstName + " " + b.MiddleName + " " + b.LastName,
                        age = b.Birthdate,
                        gender = d.NameValue,
                        regtime = c.RegistrationTime,
                        doctorid = e.DoctorId,
                        hospitalid = f.HospitalUnitId,
                        location = c.HuLobRel.RefHu.CodeBusiness,
                        lobid = g.Id,
                        istreated = b.IsTreated
                    };

            if (methodName == "Default") {

                a = a.Where(p => EntityFunctions.DiffDays(p.regtime, DateTime.Now) == 0);
            }
            if (methodName == "last7days") {
                a = a.Where(p => EntityFunctions.DiffDays(p.regtime, DateTime.Now) <= 7);
                a = a.Where(s => s.istreated == true);
            }

            if (methodName == "IsTreated") {
                a = a.Where(p => p.istreated == true);
            }

            if (methodName == "UnTreated") {
                a = a.Where(p => EntityFunctions.DiffDays(p.regtime, DateTime.Now) == 0);
                a = a.Where(p => p.istreated == false);
            }


            if (location == hospitalcode) {
                a = a.Where(p => p.hospitalid == HuId);
            } else {
                a = a.Where(p => p.hospitalid != HuId);
            }



            a = a.Where(p => p.lobid.Equals(lob_id));

            if (patient_id != 0) {
                a = a.Where(q => q.patientid.Equals(patient_id) && q.regtime.Equals(reg_time));
            }

            if (!string.IsNullOrEmpty(reg_time)) {
                DateTime regtime = DateTime.ParseExact(reg_time, HISModels.Enums.StaticVariables.DateFormat, null);
            }

            //paging.iTotalRecords = a.Count();
            a = a.Where(p => (p.FirstName.Contains(keywords) || p.MiddleName.Contains(keywords) || p.LastName.Contains(keywords) || p.mrno.Contains(keywords)));

            paging.iTotalRecords = a.Count();
            paging.iTotalDisplayRecords = a.Count();
            a = a.OrderBy(b => b.regtime);
            a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

            paging.aaData = a;

            HttpResponseMessage<DataTablesNet> returnValue = new HttpResponseMessage<DataTablesNet>(
                paging
            );
            return returnValue;
        }

        [WebGet(UriTemplate = "doctor/specialist/")]
        public HttpResponseMessage<List<RefSpecialist>> GetSpecialistDoctor() {
            HttpResponseMessage<List<RefSpecialist>> returnValue = null;
            List<RefSpecialist> listSpecialist = null;
            try {
                listSpecialist = AppContext.RefSpecialists.ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            returnValue = new HttpResponseMessage<List<RefSpecialist>>(statusCode);
            returnValue.Content = new ObjectContent<List<RefSpecialist>>(listSpecialist);
            if (listSpecialist == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/schedule/registration/paging/")]
        public HttpResponseMessage<DataTablesNet> GetDoctorScheduleForRegistration(PostDataTablesNet pagingSearch) {
            /// TODO :
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] data = null;

            string name = string.Empty;
            string code = string.Empty;
            int specialistid = 0;
            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                data = pagingSearch.sSearch.Split(';');

                name = data[0].Split('=')[1].NullSafeToString().Trim();
                code = data[1].Split('=')[1].NullSafeToString().Trim();
                specialistid = Convert.ToInt32(data[2].Split('=')[1]);
                int dd = (int)DateTime.Now.DayOfWeek;

                var a = from b in AppContext.Doctors
                        join c in AppContext.DoctorSchedules on b.Id equals c.DoctorId
                        join f in AppContext.DoctorSpecRels on b.Id equals f.DoctorId
                        join g in AppContext.RefSubSpecialists on f.SubSpecialistId equals g.Id
                        join h in AppContext.RefSpecialists on g.SpecialistId equals h.Id
                        join i in AppContext.RefSpecialistGroups on h.GroupSpecialistId equals i.Id
                        join l in AppContext.Employees on b.EmployeeId equals l.Id
                        join d in AppContext.MemberEmployees on l.Id equals d.EmployeeId
                        join e in AppContext.SysMemberships on d.MembershipId equals e.Id
                        where b.RecordStatus == 1 && c.DaySet == dd
                        select new {
                            b.Id,
                            DoctorCode = b.CodeValue,
                            l.FirstName,
                            l.LastName,
                            DoctorName = (l.FirstName.Trim() + " " + l.LastName.Trim()).Trim(),
                            GroupSpecialist = i.NameValue,
                            SubSpecialist = g.NameValue,
                            Specialist = h.NameValue,
                            SpecialistId = h.Id,
                            FullSpecialist = i.NameValue + " " + h.NameValue + " " + g.NameValue,
                            e.UserId,
                            TotalAppointment = (from j in AppContext.Appointments
                                                join o in AppContext.DoctorSchedules on j.DoctorScheduleId equals o.Id
                                                join q in AppContext.Doctors on o.DoctorId equals q.Id
                                                where q.Id == b.Id && EntityFunctions.DiffDays(j.StartTime, DateTime.Now) == 0 && j.RecordStatus == 1
                                                select j).Count(),
                            PatientQueue = (from k in AppContext.DoctorRegRels
                                            join n in AppContext.PatientRegs on k.RegistrationId equals n.Id
                                            join m in AppContext.Patients on n.PatientId equals m.Id
                                            where n.RecordStatus == 1 && EntityFunctions.DiffDays(n.RegistrationTime, DateTime.Now) == 0 && !m.IsTreated && k.DoctorId == c.DoctorId
                                            select k).Count() // TODO: 
                        };
                a = a.Distinct();

                paging.iTotalRecords = a.Count();
                a = a.Where(p => ((p.FirstName.Contains(name) || p.LastName.Contains(name) || p.DoctorName.Contains(name)) && p.DoctorCode.Contains(code)));

                if (specialistid != 0) {
                    a = a.Where(d => d.SpecialistId == specialistid);
                }

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);
            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/schedule/paging/")]
        public HttpResponseMessage<DataTablesNetAppointment> GetDoctorSchedulePost(PostDataTablesNet pagingSearch) {

            HttpResponseMessage<DataTablesNetAppointment> returnValue = null;
            List<DoctorScheduleData> listAppointment = null;
            DataTablesNetAppointment paging = null;
            string[] arrParam = null;
            string doctorName = string.Empty;
            int doctorId = 0;
            try {
                listAppointment = new List<DoctorScheduleData>();
                paging = new DataTablesNetAppointment();

                paging.sEcho = pagingSearch.sEcho;
                arrParam = pagingSearch.sSearch.Split(';');
                doctorId = Convert.ToInt32(arrParam[0].Split('=')[1]);

                //var a = (from b in AppContext.DoctorSchedules
                //         join c in AppContext.HuRooms on b.HospitalUnitRoomId equals c.Id
                //         join d in AppContext.HuWards on c.WardId equals d.Id
                //         join e in AppContext.RefHus on d.HospitalUnitId equals e.Id
                //         where b.DoctorId == doctorId
                //         select new { e.Id }).Distinct();

                var a = (from b in AppContext.DoctorSchedules
                         where b.DoctorId == doctorId
                         select new { b.HospitalUnitId }).Distinct();

                paging.iTotalRecords = a.Count();

                var l = a.ToList();

                foreach (var item in l) {
                    DoctorScheduleData appdata = new DoctorScheduleData();
                    try {
                        //var b = from c in AppContext.HuRooms
                        //        join d in AppContext.DoctorSchedules on c.Id equals d.HospitalUnitRoomId into s
                        //        from o in s.DefaultIfEmpty()
                        //        join e in AppContext.HuWards on c.WardId equals e.Id
                        //        join g in AppContext.RefHus on e.HospitalUnitId equals g.Id
                        //        where g.Id == item.Id && o.DoctorId == doctorId
                        //        select new { o.DoctorId, o.AllDay, o.DaySet, HuName = g.NameValue, o.StartScheduleTime, o.EndScheduleTime };

                        var b = from c in AppContext.DoctorSchedules
                                join d in AppContext.RefHus on c.HospitalUnitId equals d.Id
                                where c.HospitalUnitId == item.HospitalUnitId && c.DoctorId == doctorId
                                select new { c.DoctorId, c.AllDay, c.DaySet, HuName = d.NameValue, c.StartScheduleTime, c.EndScheduleTime };

                        var k = b.ToList();

                        foreach (var items in k) {
                            appdata.Location = items.HuName;
                            //appdata.ScheduleId = items.Id;

                            switch (items.DaySet) {
                                case 1:
                                    if (items.AllDay != null) {
                                        appdata.Monday = "By Appointment  ";
                                    } else {
                                        appdata.Monday = appdata.Monday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                                case 2:
                                    if (items.AllDay != null) {
                                        appdata.Tuesday = "By Appointment  ";
                                    } else {
                                        appdata.Tuesday = appdata.Tuesday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                                case 3:
                                    if (items.AllDay != null) {
                                        appdata.Wednesday = "By Appointment  ";
                                    } else {
                                        appdata.Wednesday = appdata.Wednesday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                                case 4:
                                    if (items.AllDay != null) {
                                        appdata.Thursday = "By Appointment  ";
                                    } else {
                                        appdata.Thursday = appdata.Thursday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                                case 5:
                                    if (items.AllDay != null) {
                                        appdata.Friday = "By Appointment  ";
                                    } else {
                                        appdata.Friday = appdata.Friday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                                case 6:
                                    if (items.AllDay != null) {
                                        appdata.Saturday = "By Appointment  ";
                                    } else {
                                        appdata.Saturday = appdata.Saturday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                                default:
                                    if (items.AllDay != null) {
                                        appdata.Sunday = "By Appointment  ";
                                    } else {
                                        appdata.Sunday = appdata.Sunday + new DateTime(items.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(items.EndScheduleTime.Value.Ticks).ToString("HH:mm") + ", ";
                                    }
                                    break;
                            }
                        }
                        appdata.Monday = appdata.Monday != null ? appdata.Monday.Remove(appdata.Monday.Length - 2, 2) : string.Empty;
                        appdata.Tuesday = appdata.Tuesday != null ? appdata.Tuesday.Remove(appdata.Tuesday.Length - 2, 2) : string.Empty;
                        appdata.Wednesday = appdata.Wednesday != null ? appdata.Wednesday.Remove(appdata.Wednesday.Length - 2, 2) : string.Empty;
                        appdata.Thursday = appdata.Thursday != null ? appdata.Thursday.Remove(appdata.Thursday.Length - 2, 2) : string.Empty;
                        appdata.Friday = appdata.Friday != null ? appdata.Friday.Remove(appdata.Friday.Length - 2, 2) : string.Empty;
                        appdata.Saturday = appdata.Saturday != null ? appdata.Saturday.Remove(appdata.Saturday.Length - 2, 2) : string.Empty;
                        appdata.Sunday = appdata.Sunday != null ? appdata.Sunday.Remove(appdata.Sunday.Length - 2, 2) : string.Empty;

                        listAppointment.Add(appdata);

                    } catch { }


                }
                paging.iTotalDisplayRecords = a.Count();

                //a = a.OrderBy(b => b.DoctorId);
                //a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);
                paging.aaData = listAppointment;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNetAppointment>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNetAppointment>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        ///<summary>
        /// Insert Doctor Schedule (DeserializeObject manual)
        /// </summary>
        /// <param name="paramObject"></param>
        /// <returns></returns>
        /// 
        [WebInvoke(Method = "POST", UriTemplate = "doctor/schedule/")]
        public HttpResponseMessage<DoctorSchedule> InsertDoctorSchedule(HttpRequestMessage<DoctorSchedule> paramObject) {
            HttpResponseMessage<DoctorSchedule> returnValue = null;
            DoctorSchedule doctorschedule = null;
            TimeSpan time = new TimeSpan(0, 0, 0);


            try {
                doctorschedule = JsonConvert.DeserializeObject<DoctorSchedule>(paramObject.Content.ReadAsStringAsync().Result);

                if (AppContext.DoctorSchedules.Where(d => d.DaySet == doctorschedule.DaySet && d.StartScheduleTime == time && d.EndScheduleTime == time && d.RecordStatus == 1).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                    doctorschedule = null;
                } else {
                    if (doctorschedule.HospitalUnitId == null) {
                        var a = (from c in AppContext.HuRooms
                                 join d in AppContext.HuWards on c.WardId equals d.Id
                                 where c.Id == doctorschedule.HospitalUnitRoomId
                                 select new { d.HospitalUnitId }).First();
                        doctorschedule.HospitalUnitId = a.HospitalUnitId;
                    }
                    AppContext.Entry(doctorschedule).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);

                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DoctorSchedule>(statusCode);
                returnValue.Content = new ObjectContent<DoctorSchedule>(doctorschedule);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/schedule/criteria/")]
        public HttpResponseMessage<AnonymousHeaderDetail> GetDoctorScheduleByParam(string param) {
            HttpResponseMessage<AnonymousHeaderDetail> returnValue = null;

            AnonymousHeaderDetail doctorschedule = null;
            string[] data = null;

            string start = string.Empty;
            string end = string.Empty;
            int dayset = 0;

            TimeSpan starttime = TimeSpan.Zero;
            TimeSpan endtime = TimeSpan.Zero;

            int doctorid = 0;

            try {
                data = param.Split(';');
                start = data[0].Split('=')[1].NullSafeToString();
                end = data[1].Split('=')[1].NullSafeToString();
                dayset = Convert.ToInt32(data[2].Split('=')[1]);
                doctorid = Convert.ToInt32(data[3].Split('=')[1]);

                starttime = TimeSpan.Parse(start);
                endtime = TimeSpan.Parse(end);

                doctorschedule = new AnonymousHeaderDetail();



                if (AppContext.DoctorSchedules.Where(d => d.HospitalUnitRoomId == null && d.DoctorId == doctorid && d.DaySet == dayset && d.RecordStatus == 1).Count() > 0) {
                    var a = from c in AppContext.DoctorSchedules
                            select new {
                                roomid = 0,
                                roomname = string.Empty,
                                doctorscheduleid = c.Id,
                                startschedule = c.StartScheduleTime,
                                endschedule = c.EndScheduleTime,
                                day = c.DaySet,
                                doctorid = c.DoctorId,
                                minuteperslot = c.MinutePerSlot
                            };
                    a = a.Where(p => p.startschedule == starttime && p.endschedule == endtime && p.day == dayset && p.doctorid == doctorid);
                    doctorschedule.Detail = a;
                } else {
                    var a = from c in AppContext.HuRooms
                            join d in AppContext.DoctorSchedules on c.Id equals d.HospitalUnitRoomId
                            select new {
                                roomid = c.Id,
                                roomname = c.NameValue,
                                doctorscheduleid = d.Id,
                                startschedule = d.StartScheduleTime,
                                endschedule = d.EndScheduleTime,
                                day = d.DaySet,
                                doctorid = d.DoctorId,
                                minuteperslot = d.MinutePerSlot
                            };
                    a = a.Where(p => p.startschedule == starttime && p.endschedule == endtime && p.day == dayset && p.doctorid == doctorid);
                    doctorschedule.Detail = a;
                }

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<AnonymousHeaderDetail>(statusCode);
            returnValue.Content = new ObjectContent<AnonymousHeaderDetail>(doctorschedule);
            if (doctorschedule == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/schedule/isexist/")]
        public HttpResponseMessage<bool> IsExistDoctorSchedule(string param) {
            HttpResponseMessage<bool> returnValue = null;

            string[] data = null;
            bool isexist = false;
            int dayset = 0;
            int doctorid = 0;

            try {
                data = param.Split(';');
                dayset = Convert.ToInt32(data[1].Split('=')[1]);
                doctorid = Convert.ToInt32(data[0].Split('=')[1]);

                isexist = AppContext.DoctorSchedules.Where(d => d.DoctorId == doctorid && d.DaySet == dayset).Count() > 0;

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<bool>(statusCode);
                returnValue.Content = new ObjectContent<bool>(isexist);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "doctor/schedule/")]
        public HttpResponseMessage<DoctorSchedule> UpdateDoctorSchedule(HttpRequestMessage<DoctorSchedule> paramObject) {
            HttpResponseMessage<DoctorSchedule> returnValue = null;
            DoctorSchedule doctorschedule = null;
            TimeSpan time = new TimeSpan(0, 0, 0);

            try {
                doctorschedule = JsonConvert.DeserializeObject<DoctorSchedule>(paramObject.Content.ReadAsStringAsync().Result);

                if (AppContext.DoctorSchedules.Where(d => d.DaySet == doctorschedule.DaySet && d.StartScheduleTime == time && d.EndScheduleTime == time && d.RecordStatus == 1).Count() > 0) {

                    detailMessage = "Data is already exist in Database!";

                } else {

                    AppContext.Entry(doctorschedule).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                    statusCode = HttpStatusCode.OK;
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DoctorSchedule>(statusCode);
            returnValue.Content = new ObjectContent<DoctorSchedule>(doctorschedule);
            returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "doctor/schedule/")]
        public HttpResponseMessage<DoctorSchedule> DeleteDoctorScheduleByID(int id) {
            HttpResponseMessage<DoctorSchedule> returnValue = null;
            DoctorSchedule doctorschedule = null;
            try {
                doctorschedule = AppContext.DoctorSchedules.Where(d => d.Id == id).First();
                AppContext.Entry(doctorschedule).State = System.Data.EntityState.Deleted;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DoctorSchedule>(statusCode);
                returnValue.Content = new ObjectContent<DoctorSchedule>(doctorschedule);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "doctor/registration/paging/")]
        public HttpResponseMessage<DataTablesNet> GetDoctorRegistration(PostDataTablesNet pagingSearch) {
            /// TODO :
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] data = null;

            int patientid = 0;

            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                data = pagingSearch.sSearch.Split(';');
                if (data.Count() == 1) {
                    patientid = Convert.ToInt32(data[0].Split('=')[1]);
                }

                var a = from b in AppContext.Doctors
                        join k in AppContext.Employees on b.EmployeeId equals k.Id
                        join e in AppContext.DoctorSpecRels on b.Id equals e.DoctorId
                        join g in AppContext.RefSubSpecialists on e.SubSpecialistId equals g.Id
                        join i in AppContext.RefSpecialists on g.SpecialistId equals i.Id
                        join j in AppContext.RefSpecialistGroups on i.GroupSpecialistId equals j.Id
                        join c in AppContext.DoctorRegRels on b.Id equals c.DoctorId
                        join d in AppContext.PatientRegs on c.RegistrationId equals d.Id
                        join f in AppContext.Patients on d.PatientId equals f.Id
                        join h in AppContext.DoctorHuRels on b.Id equals h.DoctorId
                        where b.RecordStatus == 1 && d.PatientId == patientid && EntityFunctions.DiffDays(d.RegistrationTime, DateTime.Now) == 0
                        select new {
                            DoctorId = c.Id,
                            DoctorCode = b.CodeValue,
                            PatientId = d.PatientId,
                            c.RegistrationId,
                            k.FirstName,
                            k.LastName,
                            FullName = k.FirstName + " " + k.LastName,
                            GroupSpecialist = j.NameValue,
                            SubSpecialist = g.NameValue,
                            Specialist = i.NameValue,
                            FullSpecialist = j.NameValue + " " + i.NameValue + " " + g.NameValue,
                            RegistrationNum = d.CodeValue,
                            d.RegistrationTime,
                            DoctorIntRefName = (from m in AppContext.Doctors
                                                join n in AppContext.Employees on m.EmployeeId equals n.Id
                                                join o in AppContext.DocRegRefRels on d.Id equals o.RegistrationId
                                                where m.Id == o.DoctorId && o.IsExtDoctor == 0
                                                select new { DocName = n.FirstName + " " + n.LastName }),
                            DoctorExtRefName = (from m in AppContext.DoctorExts
                                                join o in AppContext.DocRegRefRels on d.Id equals o.RegistrationId
                                                where o.DoctorExtId == m.Id && o.IsExtDoctor == 1
                                                select new { DocName = m.TitleBeforeName + " " + m.FullName + " " + m.TitleAfterName, Specialist = m.Specialist })
                        };


                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.DoctorId);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);
            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        #endregion

        //TODO : remove this method if its still unused
        #region Member Doctor
        [WebGet(UriTemplate = "member/doctor/{id}")]
        public HttpResponseMessage<SysMembership> GetMemberByDoctorId(int id) {
            HttpResponseMessage<SysMembership> returnValue = null;
            SysMembership sysmembership = null;
            try {
                sysmembership = (from b in AppContext.Doctors
                                 join f in AppContext.Employees on b.EmployeeId equals f.Id
                                 join d in AppContext.MemberEmployees on f.Id equals d.EmployeeId
                                 join e in AppContext.SysMemberships on d.MembershipId equals e.Id
                                 where e.Id == id
                                 select e).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysMembership>(statusCode);
                returnValue.Content = new ObjectContent<SysMembership>(sysmembership);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        #endregion

        void IDisposable.Dispose() {
            try {
                base.Dispose();
                GC.SuppressFinalize(this);
            } catch { }
        }
    }
}